﻿using homework05;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace WithFramework.Controllers
{
    [ApiController]
    public class order : ControllerBase
    {
        static OrderService orderService;
        static Order current;
        static order()
        {
            orderService = new OrderService();
            var cargos = new Cargos();
            current = new Order("you");
            orderService.AddOrder(current);
            cargos.printCargos();
            try
            {
                orderService.Import();
                Console.WriteLine("成功读取了存档数据: ");
                Console.WriteLine(JsonConvert.SerializeObject(orderService.OrderList));
            }

            catch (FileNotFoundException)
            {
                Console.WriteLine("未找到存档数据。");
            }
            Console.WriteLine("服务端初始化完毕");
        }
        [HttpGet]
        [Route("api/get")]
        public string get()
        {
            return "okkk";
        }
        [HttpPost]
        [Route("api/add")]
        public string Add(string name,int number)
        {
            try
            {
                current.AddItem(name, number);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            return JsonConvert.SerializeObject(current.Items);
        }
        [HttpPost]
        [Route("api/delete")]
        public string Delete( string name)
        {
            List<OrderItem> list = current.Items;
            OrderItem temp = null;
            foreach (var i in list)
            {
                if (i.Pname == name)
                {
                    temp = i;
                };
            }
            current.Items.Remove(temp);
            return JsonConvert.SerializeObject(current.Items);
        }
        [HttpPost]
        [Route("api/update")]
        public string Update( string name,  int number)
        {
            try
            {
                orderService.ModifyOrder(current.ID, name, number);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            return JsonConvert.SerializeObject(current.Items);
        }
        [HttpPost]
        [Route("api/query")]
        public string Query( string operate,string source)
        {
            try
            {
                return orderService.Query(operate, source);
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
    }
}
